package com.pig.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.pig.dto.Result;
import com.pig.entity.Product;
import com.pig.mapper.ProductMapper;
import com.pig.service.ProductService;
import com.pig.utils.CacheClient;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.pig.utils.RedisConstants.*;

/**
 * 商品服务实现类
 */
@Service
public class ProductServiceImpl implements ProductService {
    
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
//    @Override
//    public Product getProductById(Long id) {
//        String key = "cache:product:" + id;
//        // 1.从redis查询商铺缓存
//        String productJson = stringRedisTemplate.opsForValue().get(key);
//        // 2.判断是否存在
//        if (StrUtil.isNotBlank(productJson)) {
//            // 3.存在，直接返回
//            Product product = JSONUtil.toBean(productJson, Product.class);
//            return product;
//        }
//        // 4.不存在，根据id查询数据库
//        Product product = productMapper.selectById(id);
//        // 5.不存在，返回错误
//        if (product == null) {
//            return null;
//        }
//        // 6.存在，写入redis
//        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(product), 30L, TimeUnit.MINUTES);
//        // 7.返回
//        return product;
//        }

    @Resource
    private CacheClient cacheClient;

    @Override
    public Product getProductById(Long id) {
        // 解决缓存穿透
        Product product = cacheClient
                .queryWithPassThrough(CACHE_PRODUCT_KEY, id, Product.class, productMapper::selectById, CACHE_PRODUCT_TTL, TimeUnit.MINUTES);

        // 互斥锁解决缓存击穿
        // Product product = cacheClient
        //         .queryWithMutex(CACHE_PRODUCT_KEY, id, product.class, productMapper::selectById, CACHE_PRODUCT_TTL, TimeUnit.MINUTES);

        // 逻辑过期解决缓存击穿
        // Product product = cacheClient
        //         .queryWithLogicalExpire(CACHE_PRODUCT_KEY, id, product.class, productMapper::selectById, 20L, TimeUnit.SECONDS);

        if (product == null) {
            return null;
        }
        // 7.返回
        return product;
    }

    
    @Override
    public List<Product> getAllProducts() {
        return productMapper.selectAll();
    }
    
    @Override
    public List<Product> getProductsByCategory(Long categoryId) {
        return productMapper.selectByCategoryId(categoryId);
    }
    
    @Override
    public List<Product> searchProducts(String keyword) {
        return productMapper.searchByName(keyword);
    }
    
    @Override
    public Product addProduct(Product product) {
        product.setCreateTime(LocalDateTime.now());
        product.setUpdateTime(LocalDateTime.now());
        product.setStatus(1);
        productMapper.insert(product);
        // 单独存储库存到Redis
        stringRedisTemplate.opsForValue().set("seckill:stock:" + product.getId(), String.valueOf(product.getStock()));
        return product;
    }
    
    @Override
    public Product updateProduct(Product product) {
        product.setUpdateTime(LocalDateTime.now());
        productMapper.update(product);
        // 同步更新库存到Redis
        stringRedisTemplate.opsForValue().set("seckill:stock:" + product.getId(), String.valueOf(product.getStock()));
        return productMapper.selectById(product.getId());
    }
    
    @Override
    public boolean deleteProduct(Long id) {
        return productMapper.deleteById(id) > 0;
    }
    
    @Override
    public boolean updateStock(Long id, Integer stock) {
        return productMapper.updateStock(id, stock) > 0;
    }
} 